package cn.phecda.boot.tenant.web.filter;

import cn.phecda.boot.common.lang.model.TenantContext;
import cn.phecda.boot.common.lang.util.HttpHeaderUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

/**
 * <p> 租户过滤器 </p>
 *
 * @author : wanpinwei
 */
@Slf4j
public class TenantGenericFilterBean extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String tenantId = HttpHeaderUtils.getTenantId(req);
        TenantContext.set(tenantId);

        String url = req.getRequestURI();
        if (log.isDebugEnabled()) {
            log.debug("|Phecda Boot Tenant|- SET for request [tenantId={}, url={}]", TenantContext.get(), url);
        }
        try {
            filterChain.doFilter(req, servletResponse);
        } finally {
            TenantContext.clear();
            if (log.isDebugEnabled()) {
                log.debug("|Phecda Boot Tenant|- CLEAR for request [tenantId={}, url={}]", TenantContext.get(), url);
            }
        }
    }

}
